﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;
using GodProject.peoples;

namespace WebGodServer.Database
{
  public class DatabaseManager
  {
    private readonly DataContext database;
    public DatabaseManager(string connectionString)
    {
      database = new DataContext(connectionString) {Log = Console.Out};
    }

    public IEnumerable<SearchResult> Find(SearchQuery query)
    {
      IEnumerable<SearchResult> allPairs = GetAllPairs();


      IEnumerable<SearchResult> filtered =
        allPairs.Where(
          searchResult => ResultQueryMatcher.IsMatch(searchResult, query));

      return filtered;
    }

    private IEnumerable<SearchResult> GetAllPairs()
    {
      Table<DBStudent> students = database.GetTable<DBStudent>();
      Table<DBParent> parents = database.GetTable<DBParent>();
      Table<DBPair> pairs = database.GetTable<DBPair>();

      IQueryable<SearchResult> result =
        from st in students
        join pr in pairs on st.Id equals pr.Student_id
        join par in parents on pr.Parent_id equals par.Id
        select new SearchResult()
                 {
                   Child = (CreateStudent.Compile())(st),
                   Parent = (CreateParent.Compile())(par)
                 };
      return result;
    }

    private static readonly Expression<Func<DBStudent, Student>> CreateStudent =
      a => (a.Avg_mark <= 3
              ? new Student(a.Name, a.Sex ? Sex.Male : Sex.Female, a.Age, a.Surname)
              : new Botan(a.Name, a.Sex ? Sex.Male : Sex.Female, a.Age, a.Surname, a.Avg_mark));
    private static readonly Expression<Func<DBParent, Parent>> CreateParent =
      a => (a.Money_count > 0
              ? new CoolParent(a.Name, a.Age, a.Child_count, a.Money_count)
              : new Parent(a.Name, a.Age, a.Child_count));

  }
}
